package admin.controllers;

import helpers.PaginatorHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;

import entities.Application;
import entities.Article;
import entities.Category;

import admin.models.ApplicationModel;
import admin.models.ArticleModel;
import admin.models.CategoryModel;

public class ArticleListServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String appId = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (appId == null || appId.isEmpty()) {
			response.sendRedirect("/admin/application/list");
			return ;
		}
		
		ApplicationModel appModel = ApplicationModel.getInstance();
		Application app = appModel.get(appId);
		
		if (app == null) {
			response.sendRedirect("/admin/application/list");
			return ;
		}
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		int page = 1;
		int limit = 20;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Map<String, Category> categories = categoryModel.getMapAll(app.getId());
		
		ArticleModel articleModel = ArticleModel.getInstance();
		List<Article> articles = articleModel.getLastestArticle(appId, page, limit, language);
		
		boolean nextPage = false;
		boolean prevPage = false;
		
		if (articles.size() == limit) {
			nextPage = true;
		}
		
		if (page > 1) {
			prevPage = true;
		}
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		request.setAttribute("app", app);
		request.setAttribute("articles", articles);
		request.setAttribute("categories", categories);
		request.setAttribute("paginator", paginator);
		request.setAttribute("prevPage", prevPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("page", page);
		try {
			request.getRequestDispatcher("/admin/pages/article_list.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
